//
//  NotificationListVC.m
//  NotificationMe
//
//  Created by max on 2018/12/16.
//  Copyright © 2018年 dayang. All rights reserved.
//

#import "NotificationListVC.h"
#import "NMTableView.h"
#import "NMHomeTableViewCell.h"
#import "AddNotificationVC.h"
#import <JKAlertManager.h>
#import <UIScrollView+EmptyDataSet.h>

@interface NotificationListVC () <UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) NMTableView *tableView;

@property (nonatomic, strong) NSArray *titles;

@property (nonatomic, strong) NSMutableArray <NSMutableArray *>*dataArray;

@end

@implementation NotificationListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupViews];
    
    [self configureData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self loadData];
}

- (void)loadData {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.dataArray removeAllObjects];
            NSMutableArray *times = @[].mutableCopy;
            NSMutableArray *locations = @[].mutableCopy;
            NSMutableArray *calendars = @[].mutableCopy;
            for (UNNotificationRequest *request in requests) {
                if ([request.trigger isKindOfClass:[UNTimeIntervalNotificationTrigger class]]) {
                    [times addObject:request];
                }else if ([request.trigger isKindOfClass:[UNLocationNotificationTrigger class]]) {
                    [locations addObject:request];
                }else if ([request.trigger isKindOfClass:[UNCalendarNotificationTrigger class]]) {
                    [calendars addObject:request];
                }
            }
            [self.dataArray addObject:times];
            [self.dataArray addObject:locations];
            [self.dataArray addObject:calendars];
            [self.tableView reloadData];
        });
        
    }];
}

#pragma mark - Private Methods
- (void)setupViews {
    self.title = @"Notification Me";
    self.view.backgroundColor = [UIColor FFLightGray];
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(notificationAdd)];
}

- (void)notificationAdd {
    JKAlertManager *manager = [[JKAlertManager alloc]initWithPreferredStyle:UIAlertControllerStyleActionSheet title:@"What kind of notification do you want to add?" message:@"Time: Triggered according to time interval.\n\n Location:Trigger based on positioning at a certain location. \n\n Calendar: Trigger based on calendar time."];
    [manager configueCancelTitle:nil destructiveIndex:3 otherTitle:@"Time",@"Location",@"Calendar",@"Cancel", nil];
    [manager showAlertFromController:self actionBlock:^(JKAlertManager * _Nullable tempAlertManager, NSInteger actionIndex, NSString * _Nullable actionTitle) {
        if (![actionTitle isEqualToString:@"Cancel"]) {
            AddNotificationVC *vc = [[AddNotificationVC alloc] initWithNotificationType:actionIndex];
            [self.navigationController pushViewController:vc animated:true];
        }
    }];
}

- (void)configureData {
    self.titles = @[@"Time",@"Location",@"Calendar"];
    [_tableView reloadData];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.titles[section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray[section].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NMHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNMHomeTableViewCell forIndexPath:indexPath];
    UNNotificationRequest *request = self.dataArray[indexPath.section][indexPath.row];
    [cell updateTitle:request.content.title subtitle:@""];
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *array = self.dataArray[indexPath.section];
    UNNotificationRequest *request = array[indexPath.row];
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center removePendingNotificationRequestsWithIdentifiers:@[request.identifier]];
    [array removeObject:request];
    [self.tableView reloadData];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"Add Your Notification Now!!!";
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0f],
                                 NSForegroundColorAttributeName: [UIColor darkGrayColor]};
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

#pragma mark - Properties
- (NMTableView *)tableView {
    if (!_tableView) {
        _tableView = [[NMTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor FFLightGray];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = [NMHomeTableViewCell height];
        [_tableView registerClass:[NMHomeTableViewCell class] forCellReuseIdentifier:kNMHomeTableViewCell];
    }
    return _tableView;
}

- (NSMutableArray <NSMutableArray *>*)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

@end
